package cn.lym.zxxx.request;

import cn.lym.zxxx.session.ShareSessionManager;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ShareHttpServletRequest extends HttpServletRequestWrapper {

    /**
     * 所属session
     */
    private HttpSession httpSession;

    /**
     * session管理器
     */
    private ShareSessionManager sessionManager;

    /**
     *
     */
    private final HttpServletResponse response;

    /**
     *
     */
    private String sessionId;

    /**
     * 创建一个新的实例 ShareHttpServletRequest实例
     *
     * @param request        请求
     * @param sessionManager session管理器
     * @param response       响应
     */
    public ShareHttpServletRequest(HttpServletRequest request, ShareSessionManager sessionManager, HttpServletResponse response) {
        super(request);
        this.sessionManager = sessionManager;
        this.response = response;
        this.sessionId = findSessionId(request);
    }

    @Override
    public HttpSession getSession(boolean create) {
        if (httpSession == null) {
            httpSession = sessionManager.getOrCreateSession(sessionId, this, response, create);
        }
        return httpSession;
    }

    @Override
    public HttpSession getSession() {
        return getSession(true);
    }
    
    /**
     * 从请求中获取sessionId
     *
     * @param request 请求
     * @return sessionId
     */
    private String findSessionId(HttpServletRequest request) {
        String sessionId = request.getRequestedSessionId();
        return sessionId;
    }

    public String getSessionId() {
        return sessionId;
    }
}
